<template>
  <el-input
    v-if="props.showSearch"
    v-model="filterText"
    placeholder="输入关键词"
  />

  <el-tree
    ref="treeRef"
    v-bind="$attrs"
    :data="props.treeData"
    :props="props.fields"
    :node-key="props.nodeKey"
    :filter-node-method="filterNode"
  >
    <template #default="{ data }">
      <div>
        <span
          v-for="(item, index) in splitMarkWord(data[fields.label], filterText)"
          :key="index"
          :style="{ color: item.mark ? 'red' : '' }"
          @click="nodeClick(data)"
        >
          {{ item.text }}
        </span>
        <!-- <div :class="['com-tree-text']" @click=" (data)">
            {{
              data[defaultProps.label].substr(
                0,
                data[defaultProps.label].indexOf(filterText)
              )
            }}
            <span style="color: #f50">{{ filterText }}</span>
            {{
              data[defaultProps.label].substr(
                data[defaultProps.label].indexOf(filterText) + filterText.length
              )
            }}
          </div> -->
      </div>
    </template>
  </el-tree>
</template>

<script lang="ts" setup>
import { ref, watch } from 'vue'
import { ElTree } from 'element-plus'

import treeProps from './props'

const props = defineProps(treeProps)
const emits = defineEmits({
  nodeClick: (data) => !!data
})

interface Tree {
  [key: string]: any
}

const filterText = ref('')
const treeRef = ref<InstanceType<typeof ElTree>>()

watch(filterText, (val) => {
  treeRef.value!.filter(val)
})

const nodeClick = (data: any) => {
  emits('nodeClick', data)
}

const filterNode = (value: string, data: Tree) => {
  if (!value) return true
  return data.name.includes(value)
}

function splitMarkWord(str: string, target: any) {
  if (!target) return [{ text: str, mark: false }]
  const markWordArr = []
  while (str) {
    const atIndex = str.indexOf(target)

    if (atIndex > 0) {
      const text = str.substring(0, atIndex)
      str = str.substring(atIndex, str.length)

      markWordArr.push({
        text,
        mark: false
      })

      // const tagetText = str.substring(atIndex, target.length)
    } else if (atIndex === 0) {
      const text = str.substring(atIndex, target.length)

      str = str.substring(target.length, str.length)

      markWordArr.push({
        text,
        mark: true
      })
    } else {
      const text = str.substring(0, str.length)

      str = ''

      markWordArr.push({
        text,
        mark: false
      })
    }
  }

  return markWordArr
}

defineOptions({
  name: 'CETreeSearch',
  inheritAttrs: false
})
</script>
